<template>
    <div>
        <!-- 导航栏 -->
        <van-nav-bar title="文章详情" left-arrow @click-left="$router.back()" />

        <!-- 文章 -->
        <div class="article-wrap">
            <!-- 标题 -->
            <h1 class="title">{{ article.title }}</h1>

            <!-- 用户信息 -->
            <van-cell center class="user-info">
                <div slot="title" class="name">{{ article.aut_name }}</div>
                <van-image
                    class="avatar"
                    slot="icon"
                    fit="cover"
                    round
                    :src="article.aut_photo"
                />
                <div slot="label" class="pubdate">
                    {{ article.pubdate | relativeTime }}
                </div>
                <van-button
                    class="follow-btn"
                    round
                    size="small"
                    :loading="isFollowedLoading"
                    :type="article.is_followed ? '' : 'info'"
                    :icon="article.is_followed ? '' : 'plus'"
                    @click="onFollow"
                    >{{ article.is_followed ? '已关注' : '关注' }}</van-button
                >
            </van-cell>

            <!-- 文章内容 -->
            <div
                class="markdown-body"
                v-html="article.content"
                ref="contentRef"
            ></div>

            <!-- 评论列表 -->
            <van-cell>全部评论</van-cell>
            <comment-list
                :source="articleId"
                :list="commentList"
                @update-comment-count="totalCommentCount = $event"
                @reply-click="onReplyClick"
            ></comment-list>
        </div>

        <!-- 文章底部 -->
        <div class="article-bottom">
            <van-button
                class="comment-btn"
                round
                type="default"
                size="small"
                @click="isPostShow = true"
                >写评论</van-button
            >
            <!-- 评论数 -->
            <van-icon
                name="comment-o"
                :info="totalCommentCount"
                color="#777"
            ></van-icon>
            <!-- 收藏 -->
            <van-icon
                :color="article.is_collected ? 'orange' : '#777'"
                :name="article.is_collected ? 'star' : 'star-o'"
                @click="onCollect"
            ></van-icon>
            <!-- 点赞 -->
            <van-icon
                :color="article.attitude === 1 ? 'orange' : '#777'"
                :name="article.attitude === 1 ? 'good-job' : 'good-job-o'"
                @click="onLike"
            ></van-icon>
            <!-- 分享 -->
            <van-icon name="share" color="#777"></van-icon>
        </div>

        <!-- 发布评论弹出层 -->
        <van-popup v-model="isPostShow" position="bottom">
            <post-comment
                :target="articleId"
                @post-success="onPostSuccess"
            ></post-comment>
        </van-popup>

        <!-- 回复评论弹出层 -->
        <van-popup v-model="isReplyShow" position="bottom">
            <!-- 这里使用 v-if 的目的是让组件随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题 -->
            <reply-comment
                v-if="isReplyShow"
                :articleId="articleId"
                :comment="replyComment"
                @close="isReplyShow = false"
            ></reply-comment>
        </van-popup>
    </div>
</template>

<script>
import '@/assets/github-markdown.css'
import { getArticleDetail, addFollow, deleteFollow, addCollect, deleteCollect, addLike, deleteLike } from '@/api/article'
import { ImagePreview } from 'vant'
import CommentList from './components/comment-list'
import PostComment from './components/post-comment'
import ReplyComment from './components/reply-comment'

export default {
    name: 'Article',
    components: {
        CommentList,
        PostComment,
        ReplyComment
    },
    props: {
        // 获取动态路由参数
        articleId: {
            type: [String, Number, Object],
            required: true
        }
    },
    data () {
        return {
            // 文章详情
            article: {},
            // 关注按钮的加载状态
            isFollowedLoading: false,
            // 控制发布评论弹出层是否显示
            isPostShow: false,
            // 评论列表
            commentList: [],
            // 评论总数量
            totalCommentCount: 0,
            // 控制回复评论弹出层是否显示
            isReplyShow: false,
            // 回复的评论对象
            replyComment: {}
        }
    },
    created () {
        this.loadArticle()
    },
    computed: {},
    methods: {
        async loadArticle () {
            const { data: res } = await getArticleDetail(this.articleId)
            // console.log(res);
            this.article = res.data

            // 数据改变影响视图更新（DOM数据）不是立即的
            // 所以如果需要在修改数据之后马上操作被该数据影响的视图 DOM，需要把这个代码放到 $nextTick 中
            this.$nextTick(() => {
                this.handlePerviewImage()
            })
        },
        // 图片预览
        handlePerviewImage () {
            // 获取文章内容 DOM 容器
            const articleContent = this.$refs.contentRef
            // 获取所有的 img 标签
            const imgs = articleContent.querySelectorAll('img')
            // 所有的图片路径
            const imgPath = []
            // 循环 img 标签 注册点击事件
            imgs.forEach((item, index) => {
                imgPath.push(item.src)
                item.onclick = () => {
                    // 在事件处理函数中调用 ImagePreview() 预览
                    ImagePreview({
                        images: imgPath,
                        // 起始位置
                        startPosition: index,
                        closeable: true
                    })
                }
            })
        },
        // 点击关注
        async onFollow () {
            this.isFollowedLoading = true
            if (this.article.is_followed) {
                // 已关注，取消关注
                await deleteFollow(this.article.aut_id)
            } else {
                // 未关注，点击关注
                await addFollow(this.article.aut_id)
            }
            this.article.is_followed = !this.article.is_followed
            this.isFollowedLoading = false
        },
        // 收藏文章
        async onCollect () {
            this.$toast.loading({
                message: '操作中...',
                forbidClick: true
            })
            if (this.article.is_collected) {
                // 已收藏，取消收藏
                await deleteCollect(this.articleId)
                // this.$toast('取消收藏成功!')
            } else {
                // 未收藏，点击收藏
                await addCollect(this.articleId)
                // this.$toast('收藏成功!')
            }
            this.article.is_collected = !this.article.is_collected
            this.$toast.success(`${this.article.is_collected ? '' : '取消'}收藏成功!`)
        },
        // 点赞
        async onLike () {
            this.$toast.loading({
                message: '操作中...',
                forbidClick: true
            })
            if (this.article.attitude === 1) {
                // 已点赞，取消点赞
                await deleteLike(this.articleId)
                this.article.attitude = -1
            } else {
                // 未点赞，点击点赞
                await addLike(this.articleId)
                this.article.attitude = 1
            }
            this.$toast.success(`${this.article.attitude === 1 ? '' : '取消'}点赞成功!`)
        },
        // 发布评论
        onPostSuccess (data) {
            // 把发布成功的评论数据对象放到评论列表顶部
            this.commentList.unshift(data)

            // 发布成功后评论数量加一
            this.totalCommentCount++

            this.isPostShow = false
        },
        // 回复评论
        onReplyClick (comment) {
            this.replyComment = comment

            this.isReplyShow = true
        }
    },
    watch: {}
}
</script>

<style scoped>
.title {
    font-size: 20px;
    color: #3a3a3a;
    padding: 14px;
    background-color: #fff;
    margin: 0;
}
.user-info .avatar {
    width: 35px;
    height: 35px;
    margin-right: 8px;
}
.user-info .name {
    font-size: 12px;
    color: #333;
}
.user-info .pubdate {
    font-size: 12px;
    color: #b4b4b4;
}
.user-info .follow-btn {
    width: 70px;
    height: 29px;
    border: none;
}
.markdown-body {
    padding: 14px;
}

.article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 44px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
}
.comment-btn {
    width: 141px;
    height: 23px;
    border: 1px solid #eee;
    font-size: 15px;
    line-height: 23px;
    color: #a7a7a7;
}
.van-icon {
    font-size: 20px;
}
.van-icon .van-info {
    font-size: 11px;
    background-color: #e22829;
}

.article-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 46px;
    bottom: 44px;
    overflow-y: auto;
}
</style>
